/*
 * @Author: xiaosihan
 * @Date: 2024-07-02 15:26:55
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2024-07-05 14:16:09
 */

import * as BABYLON from "@babylonjs/core";
import { get } from "lodash";

//导入模型对象
export default class ImportMesh implements BABYLON.ISceneLoaderAsyncResult {

    constructor(url: string, scene: BABYLON.Scene) {
        this.init(url, scene);
    }

    meshes: BABYLON.AbstractMesh[] = [];
    particleSystems: BABYLON.IParticleSystem[] = [];
    skeletons: BABYLON.Skeleton[] = [];
    animationGroups: BABYLON.AnimationGroup[] = [];
    transformNodes: BABYLON.TransformNode[] = [];
    geometries: BABYLON.Geometry[] = [];
    lights: BABYLON.Light[] = [];
    spriteManagers: BABYLON.ISpriteManager[] = [];

    async init(url: string, scene: BABYLON.Scene) {
        const path = url.replace(/[\w\.]+$/, ""); // 提取文件路径
        const fileName = get(url.match(/[\w\.]+$/), [0]); // 提取文件名
        const loaderResult = await BABYLON.SceneLoader.ImportMeshAsync("", path, fileName, scene);
        debugger;

        // 创建骨骼查看器实例
        const skeletonViewer = new BABYLON.SkeletonViewer(loaderResult.skeletons[0], loaderResult.meshes[0], scene);


        Object.assign(this, loaderResult);
        this._loaded = true;
    }

    // 是否加载完成
    _loaded = false;

    // 等待加载完成
    async awaitLoaded() {
        while (!this._loaded) {
            await new Promise(resolve => setTimeout(resolve, 30));
        }
    }

    //播放动画
    async playAnimation(animationName: string, loop: boolean = true) {
        // 等待加载完成
        await this.awaitLoaded();
        //播放指定动画
        this.animationGroups.map(animationGroup => {
            if (animationName.toLocaleLowerCase() === animationGroup.name.toLocaleLowerCase()) {
                animationGroup.start(loop);
            } else {
                animationGroup.stop();
            }
        });
    }

    //设置位置
    async setPosition(x: number, z: number, y: number) {
        // 等待加载完成
        await this.awaitLoaded();
        if (this.meshes[0]) {
            this.meshes[0].position.set(x, z, y);
        }
    }

}